package com.biostime.dingdingbox.modules.bt.web;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.biostime.dingdingbox.common.config.Global;
import com.biostime.dingdingbox.common.persistence.Page;
import com.biostime.dingdingbox.common.utils.StringUtils;
import com.biostime.dingdingbox.common.web.BaseController;
import com.biostime.dingdingbox.modules.bt.entity.Plan;
import com.biostime.dingdingbox.modules.bt.service.PlanService;
import com.biostime.dingdingbox.modules.bt.service.ProjectService;

@Controller
@RequestMapping(value = "${adminPath}/bt/plan")
public class PlanContoller extends BaseController {

	@Autowired
	private PlanService planService;
	@Autowired
	private ProjectService projectService;

	@ModelAttribute
	public Plan get(@RequestParam(required = false) String id) {
		Plan entity = null;
		if (StringUtils.isNotBlank(id)) {
			entity = planService.get(id);
		}
		if (entity == null) {
			entity = new Plan();
		}
		return entity;
	}

	@RequestMapping(value = "view")
	public String view(Plan plan, HttpServletRequest request,
			HttpServletResponse response, Model model) {
		Page<Plan> page = planService.findPage(
				new Page<Plan>(request, response), plan);
		model.addAttribute("page", page);
		return "modules/bt/planList";
	}

	@RequestMapping(value = "form")
	public String form(Plan plan,
			@RequestParam(required = false) String projectid, Model model) {
		model.addAttribute("plan", plan);
		model.addAttribute("projectid", projectid);
		return "modules/bt/planForm";
	}

	@RequestMapping(value = "save")
	public String save(Plan plan,
			@RequestParam(required = false) String projectid) {
		planService.save(plan);
		if (StringUtils.isNotBlank(projectid)) {
			projectService.addApplyPlanning(projectid);
		}
		return "redirect:" + Global.getAdminPath() + "/bt/plan/view";
	}

	@RequestMapping(value = "delete")
	public String delete(
			@RequestParam(value = "ids", required = false) String idsRequest,
			Plan plan) {
		if (!StringUtils.isEmpty(idsRequest)) {
			String[] ids = idsRequest.split(",");
			planService.delete(ids);
		} else {
			String[] ids = {plan.getId()};
			planService.delete(ids);
		}
		return "redirect:" + Global.getAdminPath() + "/bt/plan/view";
	}
}
